package com.microservice.wechat.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 图片代理控制器
 * 用于解决微信图片防盗链问题，通过后端转发请求获取图片
 */
@RestController
@RequestMapping("/proxy")
public class ImageProxyController {
    
    /**
     * 代理微信图片
     * GET /api/proxy/wechat-image?url=https://mmbiz.qpic.cn/xxx
     * 
     * @param url 微信图片的原始URL
     * @return 图片字节流
     */
    @GetMapping("/wechat-image")
    public ResponseEntity<byte[]> proxyWechatImage(@RequestParam String url) {
        HttpURLConnection connection = null;
        
        try {
            // 验证URL是否来自微信服务器（安全检查）
            if (!isValidWechatUrl(url)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body("Invalid URL".getBytes());
            }
            
            // 创建URL连接
            URL imageUrl = new URL(url);
            connection = (HttpURLConnection) imageUrl.openConnection();
            
            // 设置请求头，模拟浏览器请求，绕过防盗链
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", 
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            connection.setRequestProperty("Referer", "https://mp.weixin.qq.com/");
            connection.setRequestProperty("Accept", "image/webp,image/apng,image/*,*/*;q=0.8");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            
            // 设置连接超时和读取超时
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);
            
            // 连接
            connection.connect();
            
            // 检查响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return ResponseEntity.status(responseCode)
                        .body(("Failed to fetch image: " + responseCode).getBytes());
            }
            
            // 获取图片内容类型
            String contentType = connection.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                contentType = "image/jpeg"; // 默认类型
            }
            
            // 读取图片字节流
            byte[] imageBytes = readInputStream(connection.getInputStream());
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentLength(imageBytes.length);
            // 允许缓存图片，提高性能
            headers.setCacheControl("public, max-age=86400"); // 缓存1天
            
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
            
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(("Error fetching image: " + e.getMessage()).getBytes());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    
    /**
     * 验证URL是否来自微信服务器
     * 
     * @param url 图片URL
     * @return 是否有效
     */
    private boolean isValidWechatUrl(String url) {
        if (url == null || url.isEmpty()) {
            return false;
        }
        
        // 微信图片常见域名
        String[] validDomains = {
            "mmbiz.qpic.cn",
            "mmbiz.qlogo.cn",
            "wx.qlogo.cn",
            "thirdwx.qlogo.cn"
        };
        
        try {
            URL imageUrl = new URL(url);
            String host = imageUrl.getHost();
            
            for (String domain : validDomains) {
                if (host.endsWith(domain)) {
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        
        return false;
    }
    
    /**
     * 读取输入流为字节数组
     * 
     * @param inputStream 输入流
     * @return 字节数组
     * @throws Exception 读取异常
     */
    private byte[] readInputStream(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        
        return outputStream.toByteArray();
    }
}
